const path = require("path")
const resolve = (dir) => path.resolve(__dirname, dir)
const CracoLessPlugin = require("craco-less")
// const HtmlWebpackPlugin = require("html-webpack-plugin")
// 环境变量
const dotenv = require("dotenv")
console.log(process.env.NODE_ENV)
// 根据当前的 NODE_ENV 变量加载不同的 .env 文件
const envFilePath =
	process.env.NODE_ENV === "production" ? ".env.production" : ".env.development"
// 加载环境变量
dotenv.config({
	path: path.resolve(__dirname, envFilePath),
})
// gzip压缩插件
const compressionWebpackPlugin = require("compression-webpack-plugin")
// 打包体积预览插件
const webpackBundleAnalyzer =
	require("webpack-bundle-analyzer").BundleAnalyzerPlugin
// 导入less全局变量
const lessVars = require(resolve("src/styles/less/modifyVars"))
const golbalVars = require(resolve("src/styles/less/variables"))
// const { loaderByName, addAfterLoader } = require("@craco/craco")
// 该配置会和webpack配置整合
module.exports = {
	plugins: [
		{
			plugin: CracoLessPlugin,
			options: {
				lessLoaderOptions: {
					lessOptions: {
						modifyVars: lessVars,
						javascriptEnabled: true,
						//配置全局less 变量，不需要在使用的地方导入了
						globalVars: golbalVars,
					},
				},
			},
		},
	],

	// 代理服务
	devServer: {
		port: 8080,
		proxy: {
			[process.env.REACT_APP_BASE_API]: {
				target: process.env.REACT_APP_SERVE,
				changeOrigin: true,
				pathRewrite: (path) => path.replace(/^\/api/, ""),
			},
		},
	},
	webpack: {
		// 路径别名
		alias: {
			"@": path.resolve(__dirname, "src"),
			"@/": resolve("src/"),
		},
		configure: (webpackConfig, { env }) => {
			/* addAfterLoader(webpackConfig, loaderByName("sass-loader"), {
				// 配置sass全局变量，如果配置完使用全局变量报错，说明包没下好
				loader: require.resolve("sass-resources-loader"),
				options: {
					resources: [resolve("src/styles/sass/variables.scss")],
				},
			}) */
			webpackConfig.entry = resolve("src/index.tsx")
			webpackConfig.output = Object.assign({}, webpackConfig.output, {
				filename: "js/[name][chunkhash:5].js",
				chunkFilename: "js/[name].[chunkhash:5].chunk.js",
				assetModuleFilename: "static/[ext]/[name].[hash][ext]",
			})
			webpackConfig.module.rules.push({
				// ... other config
				test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
				use: [
					{
						loader: "@svgr/webpack",
						options: {
							babel: false,
							icon: true,
						},
					},
				],
			})
			// console.log(webpackConfig.module.rules)
			webpackConfig.resolve.extensions = [
				...webpackConfig.resolve.extensions,
				...[".ts", ".tsx"],
			]
			// source-map
			webpackConfig.devtool =
				env === "production" ? false : "cheap-module-source-map"

			// 指定html模板
			const htmlPluginIndex = webpackConfig.plugins.findIndex(
				(plugin) => plugin.constructor.name === "HtmlWebpackPlugin",
			)

			if (htmlPluginIndex >= 0) {
				const oldHtmlPlugin = webpackConfig.plugins[htmlPluginIndex]
				webpackConfig.plugins.splice(htmlPluginIndex, 1)

				webpackConfig.plugins.push(
					new oldHtmlPlugin.constructor({
						...oldHtmlPlugin.options,
						template: path.resolve(__dirname, "public/index.html"), // 指定自定义HTML模板路径
					}),
				)
			}
			// console.log(webpackConfig)
			if (env === "production") {
				// gzip
				webpackConfig.plugins.push(
					new compressionWebpackPlugin({
						filename: "[path][name].gz",
						algorithm: "gzip",
						// test: /.js$|.html$|.json$|.css/,
						test: /.js$|.json$|.css$|.ts$|.tsx$|.less/,
						threshold: 10240, // 只有大小大于该值的资源会被处理
						minRatio: 0.8, // 只有压缩率小于这个值的资源才会被处理
						// deleteOriginalAssets: true // 删除原文件
					}),
				)
				// 打包优化
				webpackConfig.optimization = {
					minimize: true,
					// 代码分割配置
					splitChunks: {
						chunks: "all",
						cacheGroups: {
							// layouts通常是admin项目的主体布局组件，所有路由组件都要使用的
							// 可以单独打包，从而复用
							// 如果项目中没有，请删除
							layouts: {
								name: "layouts",
								test: path.resolve(__dirname, "../src/layouts"),
								priority: 40,
							},
							// 如果项目中使用antd，此时将所有node_modules打包在一起，那么打包输出文件会比较大。
							// 所以我们将node_modules中比较大的模块单独打包，从而并行加载速度更好
							// 如果项目中没有，请删除
							antd: {
								name: "chunk-antd",
								test: /[\\/]node_modules[\\/]antd(.*)/,
								priority: 30,
							},
							// 将react相关的库单独打包，减少node_modules的chunk体积。
							react: {
								name: "react",
								test: /[\\/]node_modules[\\/]react(.*)?[\\/]/,
								chunks: "initial",
								priority: 20,
							},
							libs: {
								name: "chunk-libs",
								test: /[\\/]node_modules[\\/]/,
								priority: 10, // 权重最低，优先考虑前面内容
								chunks: "initial",
							},
						},
					},
					runtimeChunk: {
						name: (entrypoint) => `runtime~${entrypoint.name}`,
					},
				}
				// 打包体积分析
				webpackConfig.plugins.push(new webpackBundleAnalyzer())
			}
			return webpackConfig
		},
	},
}
